package com.hoffm59.facebookcontactsync;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

public class MainActivity
        extends FragmentActivity {

    private static final int SPLASH = 0;
    private static final int SELECTION = 1;
    private static final int SETTINGS = 2;
    private static final int FRAGMENT_COUNT = MainActivity.SETTINGS + 1;

    private boolean isResumed = false;
    private MenuItem settings;

    private final Fragment[] fragments = new Fragment[MainActivity.FRAGMENT_COUNT];

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        this.uiHelper = new UiLifecycleHelper(this, this.callback);
        this.uiHelper.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_main);

        final FragmentManager fm = this.getSupportFragmentManager();
        this.fragments[MainActivity.SPLASH] = fm.findFragmentById(R.id.main_fragment_splash);
        this.fragments[MainActivity.SELECTION] = fm.findFragmentById(R.id.main_fragment_selection);
        this.fragments[MainActivity.SETTINGS] = fm.findFragmentById(R.id.userSettingsFragment);

        final FragmentTransaction transaction = fm.beginTransaction();
        for (int i = 0; i < this.fragments.length; i++) {
            transaction.hide(this.fragments[i]);
        }
        transaction.commit();
    }

    private void showFragment(int fragmentIndex, boolean addToBackStack) {

        final FragmentManager fm = this.getSupportFragmentManager();
        final FragmentTransaction transaction = fm.beginTransaction();
        for (int i = 0; i < this.fragments.length; i++) {
            if (i == fragmentIndex) {
                transaction.show(this.fragments[i]);
            } else {
                transaction.hide(this.fragments[i]);
            }
        }
        if (addToBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.commit();
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {

        // Only make changes if the activity is visible
        if (this.isResumed) {
            final FragmentManager manager = this.getSupportFragmentManager();
            // Get the number of entries in the back stack
            final int backStackSize = manager.getBackStackEntryCount();
            // Clear the back stack
            for (int i = 0; i < backStackSize; i++) {
                manager.popBackStack();
            }
            if (state.isOpened()) {
                // If the session state is open:
                // Show the authenticated fragment
                this.showFragment(MainActivity.SELECTION, false);
            } else if (state.isClosed()) {
                // If the session state is closed:
                // Show the login fragment
                this.showFragment(MainActivity.SPLASH, false);
            }
        }
    }

    private UiLifecycleHelper uiHelper;
    private final Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {

            MainActivity.this.onSessionStateChange(session, state, exception);
        }
    };

    @Override
    protected void onResumeFragments() {

        super.onResumeFragments();
        final Session session = Session.getActiveSession();

        if ((session != null) && session.isOpened()) {
            // if the session is already open,
            // try to show the selection fragment
            this.showFragment(MainActivity.SELECTION, false);
        } else {
            // otherwise present the splash screen
            // and ask the user to login.
            this.showFragment(MainActivity.SPLASH, false);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        // only add the menu when the selection fragment is showing
        if (this.fragments[MainActivity.SELECTION].isVisible()) {
            if (menu.size() == 0) {
                this.settings = menu.add(R.string.menu_settings);
            }
            return true;
        } else {
            menu.clear();
            this.settings = null;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.equals(this.settings)) {
            this.showFragment(MainActivity.SETTINGS, true);
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {

        super.onResume();
        this.uiHelper.onResume();
        this.isResumed = true;
    }

    @Override
    public void onPause() {

        super.onPause();
        this.uiHelper.onPause();
        this.isResumed = false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        this.uiHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        this.uiHelper.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        this.uiHelper.onSaveInstanceState(outState);
    }

}
